import argparse
import os
import sys

import command


def git_merge():
    parser = argparse.ArgumentParser(description='git 双向合并')
    parser.add_argument('-s', '--source', nargs='?', default='dev', help='合并到该分支')
    parser.add_argument('-t', '--target', nargs='?', default='feature/zx', help='从该分支合并')
    args, unknown_args = parser.parse_known_args()
    source = args.source
    target = args.target
    if len(unknown_args) > 0:
        source = unknown_args[0]

    if len(unknown_args) > 1:
        source = unknown_args[0]
        target = unknown_args[1]

    before_command = "git diff --stat"
    read = os.popen(before_command).read()
    if len(read) > 0:
        print(read)
        print("有文件更改, 请先缓存或提交")
        sys.exit()
    two_way_merge(source, target)


def two_way_merge(source, target):
    command_line1 = [
        f"git checkout {source}",
        f"git pull origin {source}",
        f"git merge origin/{target} --no-commit --no-ff"
    ]
    code = command.exe_command(command_line1)
    if code == 0:
        print(f"Merge branch {target} into {source} Successfully")

        command.exe_command(f'git commit -m "Merge branch {target} into {source}"')
        command.exe_command(f"git push origin {source}")

        command_line2 = [
            f"git checkout {target}",
            f"git merge origin/{source} --no-commit --no-ff",
        ]

        code2 = command.exe_command(command_line2)
        if code2 == 0:

            command.exe_command(f'git commit -m "Merge branch {source} into {target}"')
            command.exe_command(f"git push origin {target}")

            print(f"Merge branch {source} into {target} Successfully")
        else:
            print(f"Merge branch {source} into {target} Failed")
    else:
        print(f"Merge branch {target} into {source} Failed")


if __name__ == '__main__':
    git_merge()
